package org.dromara.system.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;

import org.dromara.common.core.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class OssUtil {

	// 阿里云oss配置
	private static final String accessKeyId = "LTAI5tMAarzRavnvRqT3en3R";
	private static final String accessKeySecret = "ix2utQNgdAczpd6RmXZsG9eL4iqz1k";
	// url
	public static String http = "https://";
	public static String endpoint = "oss-cn-beijing.aliyuncs.com";
	public static String urlpath = "ahyzl-file.oss-cn-beijing.aliyuncs.com";

	public static String bucket = "ahyzl-file";

	// 初始化一个OSSClient
	static OSSClient client = new OSSClient(http + endpoint, accessKeyId,
			accessKeySecret);

	public static String[] chars = new String[]
			{
					"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
					"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
					"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
			};

	public static String getShortUuid() {
		StringBuffer stringBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 8; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int strInteger = Integer.parseInt(str, 16);
			stringBuffer.append(chars[strInteger % 0x3E]);
		}

		return stringBuffer.toString();
	}



	// 上传文件  （参数类型为MultipartFile）
	public static String uploadAliMulti(MultipartFile file,String zlgd,String fileName) throws Exception{
		// 从输入流上传(需提前告知输入流的长度, 否则可能导致oom)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		if(StringUtils.isEmpty(fileName)){
			fileName = file.getOriginalFilename();
		}
		fileName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
		String savePath = "zmsj/" + ymd + "/"+getShortUuid()+fileName;
		if(StringUtils.isNotEmpty(zlgd)){
			savePath = "zmsj/" +zlgd +"/"+ ymd + "/"+getShortUuid()+fileName;
		}

		InputStream inputStream = file.getInputStream();

		String path = postStreamToAliyun(inputStream,savePath);
		inputStream.close();
		return path;
	}

//
//	/**
//	 * 上传文件到阿里云服务器
//	 *
//	 * @param is文件流
//	 * @param key
//	 *            阿里云识别图片用
//	 * @return String
//	 */
	public static String postStreamToAliyun(InputStream input, String key) {
		try {
			ObjectMetadata objectMeta = new ObjectMetadata();
			// 设置content长度
			objectMeta.setContentLength(input.available());
			// 可以在metadata中标记文件类型
			objectMeta.setContentType("application/octet-stream");
			PutObjectResult record = client.putObject(bucket, key, input,
					objectMeta);
			// 错误etag为文件的md5值
			if (record.getETag() == null || record.getETag().length() != 32) {
				return null;
			}
			return http + urlpath + "/" + key;
		} catch (OSSException o) {
			o.printStackTrace();
			// setErrorCode(ErrorCodeUtil.NO_IO_AUTHORITY);
			return null;
		} catch (ClientException c) {
			c.printStackTrace();
			// setErrorCode(ErrorCodeUtil.NO_IO_AUTHORITY);
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			// setErrorCode( ErrorCodeUtil.NO_FIND);
			return null;
		}
	}
//
//	/**
//	 * 上传文件到阿里云服务器
//	 *
//	 * @param is文件流
//	 * @param key
//	 *            阿里云识别图片用
//	 * @return String
//	 */
	public static String postFileToAliyun(File file, String key) {
		// ensureBucket(client, bucket);
		try {
			// setBucketPublicReadable(client, bucket);
			ObjectMetadata objectMeta = new ObjectMetadata();
			// 设置content长度
			objectMeta.setContentLength(file.length());
			// 可以在metadata中标记文件类型
			objectMeta.setContentType("application/octet-stream");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			String upload_path = "uploadvoide";
			// 文件保存目录路径
			String savePath = upload_path + "/" + ymd + "/";
			PutObjectResult record = client.putObject(bucket, savePath + key,
					file);
			// De record1 = client.deleteObject(bucket, key);
			// 错误etag为文件的md5值
			if (record.getETag() == null || record.getETag().length() != 32) {
				// setErrorCode(ErrorCodeUtil.IS_FAIL);
				return null;
			}
			return http + urlpath + "/" + savePath + key;
		} catch (OSSException o) {
			o.printStackTrace();
			// setErrorCode(ErrorCodeUtil.NO_IO_AUTHORITY);
			return null;
		} catch (ClientException c) {
			c.printStackTrace();
			// setErrorCode(ErrorCodeUtil.NO_IO_AUTHORITY);
			return null;
		} finally {
			// client.shutdown();
		}
	}

	// 创建Bucket.
	private static void ensureBucket(OSSClient client, String bucketName)
			throws OSSException, ClientException {
		try {
			// 创建bucket
			client.createBucket(bucketName);
		} catch (ServiceException e) {
			if (!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())) {
				// 如果Bucket已经存在，则忽略
				throw e;
			}
		}
	}

	// 把Bucket设置为所有人可读
	private static void setBucketPublicReadable(OSSClient client,
			String bucketName) throws OSSException, ClientException {
		// 创建bucket
		client.createBucket(bucketName);
		// 设置bucket的访问权限，public-read-write权限
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}

	// 删除图片，
	public static void delekey(String url) {
		if (url == null || url.indexOf(".com/") == -1) {
			return;
		}
		// 获取url 中的key。
		String key = url.substring(url.indexOf(".com/")).substring(5);

		// 删除 图片
		client.deleteObject(bucket, key);
	}

	// 删除一个Bucket和其中的Objects
	private static void deleteBucket(OSSClient client, String bucketName)
			throws OSSException, ClientException {

		ObjectListing ObjectListing = client.listObjects(bucketName);
		List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
		for (int i = 0; i < listDeletes.size(); i++) {
			String objectName = listDeletes.get(i).getKey();
			// 如果不为空，先删除bucket下的文件
			client.deleteObject(bucketName, objectName);
		}
		client.deleteBucket(bucketName);
	}

	// 下载文件
	public static void downloadFile(
			String key, String filename) throws OSSException, ClientException {
		client.getObject(new GetObjectRequest(bucket, key), new File(
				filename));
	}

	/**
	 * 生成访问URL
	 *
	 * @param key
	 * @return
	 */
	public static String readVoide(String key) {
		// 设置URL过期时间为1小时
		Date expiration = new Date(new Date().getTime() + 3600 * 1000);
		// 生成URL
		URL url = client.generatePresignedUrl(bucket, key, expiration);
		System.out.println(url.getQuery());
		String ss = url.getPath();
		return ss;
	}


	/**
	 * 列取bucket下面文件
	 *
	 * @return
	 */
	public static List<OSSObjectSummary> objectList(String key) {
		ObjectListing objectListing = client.listObjects(bucket, key);
		List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}
		return sums;
	}



}
